import EvaluationRecord from '@/components/EvaluationRecord';
import GuidanceRecord from '@/components/GuidanceRecord';
import HealthRecords from '@/components/HealthRecords';
import PhysiologicalMonitoring from '@/components/PhysiologicalMonitoring';
import TrainingRecord from '@/components/TrainingRecord';
import {
  get_platform_guidance_info,
  platform_chatLog_list,
  platform_guidance_patients,
  submit_platform_guidance,
} from '@/services/guide';
import { get_patient_info } from '@/services/patient';
import age from '@/utils/age';
import timeToHms from '@/utils/time';
import { ActionType, ProColumns, ProDescriptions, ProTable } from '@ant-design/pro-components';
import { Button, Card, Divider, message, Modal, Spin, Tabs } from 'antd';
import TextArea from 'antd/es/input/TextArea';
import { useEffect, useRef, useState } from 'react';

interface Iprops {
  isShowRemoteModal: (show: boolean) => void;
  remoteModal: boolean;
  remodeId: number | undefined;
  //   actionRef: React.MutableRefObject<ActionType | undefined>;
}
type GithubIssueItem = {
  id: number;
  time: string;
  call_type: number;
  create_time: string;
  status: number;
  status_d: string;
};
// 指导内容
var chat_content = '';

const RemoteGuide = (props: Iprops) => {
  const { isShowRemoteModal, remoteModal, remodeId } = props;
  const actionRef = useRef<ActionType>();
  // 存储患者信息
  const [patientinfo, setPatientInfo] = useState<any>(undefined);
  // 存储指导患者列表
  const [guidePatient, setGuidePatient] = useState<any>(undefined);
  // 存储患者id
  const [patientId, setPatientId] = useState<number>();
  // 存储指导详情
  const [guideInfo, setGuideInfo] = useState<any>(undefined);
  // 是否有有效的通话记录
  const [saveflag, setsaveflag] = useState(false);

  useEffect(() => {
    // 获取指导详情信息
    const guideInfo = async () => {
      if (remodeId) {
        let res: any = await get_platform_guidance_info({ id: remodeId });
        console.log('指导详情', res);
        if (res.code == 200) {
          setGuideInfo(res.data);
        }
      }
    };
    // 获取指导患者列表
    const get_patient_list = async () => {
      if (remodeId) {
        let res: any = await platform_guidance_patients({ id: remodeId });
        console.log('指导患者列表', res);
        if (res.code == 200) {
          setGuidePatient(res.data);
          // 获取患者详情
          let params: any = await get_patient_info({ id: res.data[0].patient_id });
          console.log('params', params);
          setPatientInfo(params.data);
          setPatientId(params.data.id);
        }
      }
    };
    guideInfo();
    get_patient_list();
  }, []);

  // 切换患者用户
  const onChange = async (activeKey: string) => {
    console.log('gggg', activeKey);
    let params: any = await get_patient_info({ id: activeKey });
    if (params.code == 200) {
      setPatientInfo(params.data);
      setPatientId(params.data.id);
    }
  };

  //获取呼叫记录
  const get_patient_callLog_list = async (params: {
    pageSize?: number | undefined;
    current?: number | undefined;
    keyword?: string | undefined;
  }) => {
    let request_body = {
      ...params,
      pcurrent: params.current,
      pageSize: params.pageSize,
      platform_guidance_id: remodeId,
    };
    let res = await platform_chatLog_list(request_body);
    console.log('呼叫记录', res);
    // 是否有有效通话记录
    setsaveflag(res.data.save_flag == 1);
    return {
      data: res.data.list,
      success: true,
      total: res.data.total_count,
    };
  };

  // 呼叫跳转 视频
  const send_call = () => {
    console.log('remodeId', remodeId, patientId);
    if (remodeId && patientId) {
      window.open(`/guide/my_guide/remote_video?id=${remodeId}&patient_id=${patientId}`);
    }
  };
  window.addEventListener('message', function (event: any) {
    // 在父窗口中显示子窗口发来的消息
    console.log('fff', event.data);
    if (event.data == 'remoteRefresh') {
      actionRef.current?.reload();
    }
  });
  window.addEventListener('message', function (event: any) {
    // 在父窗口中显示子窗口发来的消息
    console.log('fff', event.data);
    if (event.data == 'remoteClose') {
      isShowRemoteModal(false);
    }
  });

  //修改指导记录
  const onChangecontent = (e: { target: { value: string } }) => {
    chat_content = e.target.value;
  };

  // 结束指导
  const end_guide = async () => {
    if (chat_content.replace(/^\s\s*/, '').replace(/\s\s*$/, '') == '') {
      message.warning('请填写指导记录');
      return;
    }
    let request_body = {
      id: remodeId,
      content: chat_content,
    };
    let res: any = await submit_platform_guidance(request_body);
    if (res.msg == 'ok') {
      message.success('指导已结束');
      isShowRemoteModal(false);
      setTimeout(() => {
        window.close();
      }, 500);
    } else {
      message.error(res.msg);
    }
  };

  // 通话记录
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      align: 'center',
    },
    {
      title: '通话时间',
      dataIndex: 'create_time',
      align: 'center',
    },
    {
      title: '通话时长',
      dataIndex: 'time',
      align: 'center',
      render: (_, record) => {
        if (record.status != 3) {
          return record.status_d;
        } else {
          return timeToHms(record.time);
        }
      },
    },
  ];
  return (
    <Modal
      title="远程指导"
      open={remoteModal}
      onCancel={() => isShowRemoteModal(false)}
      width={1500}
      destroyOnClose={true}
      footer={null}
    >
      <Divider />
      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <Button
          key="video"
          style={{ padding: '0 12px', margin: '0 20px 20px 0' }}
          type="primary"
          onClick={() => send_call()}
        >
          视频指导
        </Button>
        <Button key="end" style={{ padding: '0 12px', margin: '0 20px 20px 0' }} type="primary" onClick={() => end_guide()}>
          结束指导
        </Button>
      </div>
      {guideInfo === undefined ? (
        ''
      ) : (
        <Card>
          <ProDescriptions
            dataSource={guideInfo}
            column={4}
            columns={[
              {
                title: '机构名称',
                key: 'platform_name',
                dataIndex: 'platform_name',
              },
              {
                title: '预约账号',
                key: 'platform_phone',
                dataIndex: 'platform_phone',
              },
              {
                title: '计划指导时间',
                dataIndex: 'plan_time',
                hideInSearch: true,
              },
              {
                title: '备注',
                key: 'remark',
                dataIndex: 'remark',
              },
            ]}
          ></ProDescriptions>
        </Card>
      )}

      <div style={{ display: 'flex', marginTop: '10px' }}>
        <div style={{ flex: 4 }}>
          <Tabs
            defaultActiveKey="通话记录"
            style={{ minHeight: '750px' }}
            items={[
              {
                key: '通话记录',
                label: '通话记录',
                children: (
                  <ProTable<GithubIssueItem>
                    columns={columns}
                    actionRef={actionRef}
                    cardBordered
                    request={async (params = {}) => get_patient_callLog_list(params)}
                    editable={{
                      type: 'multiple',
                    }}
                    rowKey={(record) => record.id}
                    search={false}
                    options={false}
                    pagination={{
                      pageSize: 10,
                    }}
                    dateFormatter="string"
                    headerTitle=""
                  />
                ),
              },
              {
                key: '患者列表',
                label: '患者列表',
                children: (
                  <>
                    {guidePatient === undefined && patientinfo === undefined ? (
                      <div
                        style={{
                          margin: '20px 0',
                          marginBottom: '20px',
                          padding: '30px 50px',
                          textAlign: 'center',
                        }}
                      >
                        <Spin size="large" />
                      </div>
                    ) : (
                      <Tabs
                        type="card"
                        tabPosition="left"
                        onChange={onChange}
                        items={guidePatient.map((item: any, index: number) => {
                          return {
                            label: (
                              <>
                                <img
                                  style={{ width: '30px', height: '30px', borderRadius: '50%' }}
                                  src={
                                    item.patient_headimg ? item.patient_headimg : '/head_img.svg'
                                  }
                                  alt=""
                                />
                                <span style={{ marginLeft: '20px' }}>{item.patient_name}</span>
                              </>
                            ),
                            key: item.patient_id,
                            children: (
                              <>
                                <ProDescriptions
                                  dataSource={patientinfo}
                                  columns={[
                                    {
                                      title: '手机号',
                                      key: 'phone',
                                      dataIndex: 'phone',
                                    },
                                    {
                                      title: '姓名',
                                      key: 'username',
                                      dataIndex: 'username',
                                    },
                                    {
                                      title: '性别',
                                      key: 'sex',
                                      dataIndex: 'sex',
                                      valueType: 'select',
                                      valueEnum: {
                                        0: {
                                          text: '未知',
                                        },
                                        1: {
                                          text: '男',
                                        },
                                        2: {
                                          text: '女',
                                        },
                                      },
                                    },
                                    {
                                      title: '身份证号',
                                      key: 'id_card',
                                      dataIndex: 'id_card',
                                    },
                                    {
                                      title: '年龄',
                                      key: 'age',
                                      dataIndex: 'age',
                                      render: (_, record) => age(record.birth),
                                    },
                                    {
                                      title: '家庭地址',
                                      key: 'address',
                                      dataIndex: 'address',
                                      render: (_, record) => {
                                        return (
                                          record.province_name +
                                          record.city_name +
                                          record.area_name +
                                          record.family_address
                                        );
                                      },
                                    },
                                  ]}
                                ></ProDescriptions>
                                <Tabs
                                  defaultActiveKey="生理监测"
                                  items={[
                                    {
                                      key: '生理监测',
                                      label: '生理监测',
                                      children: (
                                        <PhysiologicalMonitoring
                                          patientId={patientId}
                                        ></PhysiologicalMonitoring>
                                      ),
                                    },
                                    {
                                      key: '评估记录',
                                      label: '评估记录',
                                      children: (
                                        <EvaluationRecord
                                          type={false}
                                          patientId={patientId}
                                        ></EvaluationRecord>
                                      ),
                                    },
                                    {
                                      key: '训练记录',
                                      label: '训练记录',
                                      children: (
                                        <TrainingRecord patientId={patientId}></TrainingRecord>
                                      ),
                                    },
                                    {
                                      key: '指导记录',
                                      label: '指导记录',
                                      children: (
                                        <GuidanceRecord patientId={patientId}></GuidanceRecord>
                                      ),
                                    },
                                    {
                                      key: '健康档案',
                                      label: '健康档案',
                                      children: (
                                        <HealthRecords info={patientinfo?.info}></HealthRecords>
                                      ),
                                    },
                                  ]}
                                // onChange={onChange}
                                />
                              </>
                            ),
                          };
                        })}
                      />
                    )}
                  </>
                ),
              },
            ]}
          />
        </div>
        <div
          style={{
            marginLeft: '20px',
            // flex: 1,
            // border: '1px solid #eee',
            display: 'flex',
            flexDirection: 'column',
            minHeight: '500px',
          }}
        >
          <TextArea
            style={{ height: '100%' }}
            name="text"
            onChange={onChangecontent}
            placeholder="请输入指导内容/记录/指导意见"
          />
        </div>
      </div>
    </Modal>
  );
};
export default RemoteGuide;
